import React, {PureComponent} from "react";
import {connect} from 'react-redux';
import {actions} from '../store'
import '../style.css'

import {Tabs} from 'antd-mobile';
import ListViewComponent from "./ListViewComponent";

class MainComponent extends PureComponent {

    state = {
        tabs: [],
        currTab: 0,
    };

    componentDidMount() {
        this.props.getArticleType((typeData) => {
            let tabs = [{title: '全部', sub: 0}];
            typeData.forEach((currentValue, index) => {
                tabs.push({title: currentValue.typeName, sub: index + 1});
            });
            let currTab = 0;
            let currTabStr = localStorage.getItem('currTab');
            if (currTabStr != null) {
                currTab = parseInt(currTabStr);
            }
            this.setState({tabs, currTab})
        });
    }

    onChange = (tab, index) => {
        this.setState({'currTab': index}, () => {
            localStorage.setItem('currTab', index);
        });
    };

    render() {
        const {tabs, currTab} = this.state;
        return (
            <Tabs tabs={tabs}
                  initialPage={0}
                  page={currTab}
                  renderTab={tab => <div>{tab.title}</div>}
                  distanceToChangeTab={0.5}
                  onChange={this.onChange}
                  onTabClick={(tab, index) => {
                      // console.log('onTabClick', index, tab);
                  }}
                  renderTabBar={props => <Tabs.DefaultTabBar {...props} page={3.5}/>}
            >
                {
                    tabs.map((item, index) => {
                        return <ListViewComponent key={index} name={item.title}/>;
                    })
                }
            </Tabs>
        )
    }
}

const mapState = (state) => ({
    typeData: state.getIn(['home', 'typeData']),
});

const mapDispatch = (dispatch) => ({
    getArticleType(callback) {
        dispatch(actions.getArticleType(callback))
    },
});

export default connect(mapState, mapDispatch)(MainComponent);